import axios, { AxiosRequestConfig, AxiosResponse, AxiosError, AxiosPromise } from 'axios';
import { ResponseBody } from '@/api/typing';
import { localStorage } from '@/utils/local-storage';
import { STORAGE_TOKEN_KEY } from '@/store/mutation-type';
import { notification } from 'ant-design-vue';
import router from '@/router';
import { useRouter } from 'vue-router';
import qs from 'qs';

// 这里是用于设定请求后端时，所用的 Token KEY
// 可以根据自己的需要修改，常见的如 Access-Token，Authorization
// 需要注意的是，请尽量保证使用中横线`-` 来作为分隔符，
// 避免被 nginx 等负载均衡器丢弃了自定义的请求头
export const REQUEST_TOKEN_KEY = 'auth_token';

// axios.defaults.withCredentials = true;// 允许跨域携带cookie
// axios.defaults.crossDomain = true
// 创建 axios 实例
const request = axios.create({
  //   withCredentials:true,
  // API 请求的默认前缀
  baseURL: (window as any).g.baseURL,
  //   baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 60000, // 请求超时时间
});

// 异常拦截处理器
const errorHandler = (error: AxiosError): Promise<any> => {
  if (error.response) {
    const { data = {}, status, statusText } = error.response;
    // 403 无权限
    if (status === 403) {
      notification.error({
        message: 'Forbidden',
        description: (data && data.message) || statusText,
      });
    }
    // 401 未登录/未授权
    if (status === 401 && data.result && data.result.isLogin) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed',
      });
    }
  }
  return Promise.reject(error);
};

// 请求拦截器
const requestHandler = (
  config: AxiosRequestConfig,
): AxiosRequestConfig | Promise<AxiosRequestConfig> => {
  const savedToken = localStorage.get(STORAGE_TOKEN_KEY);
  // 如果 token 存在
  // 让每个请求携带自定义 token, 请根据实际情况修改
  if (savedToken) {
    config.headers[REQUEST_TOKEN_KEY] = savedToken;
  }
  return config;
};

// Add a request interceptor
request.interceptors.request.use(requestHandler, errorHandler);

// 响应拦截器
const responseHandler = (
  response: AxiosResponse,
): ResponseBody<any> | AxiosResponse<any> | Promise<any> | any => {
  const data = response.data;
  if (data.code === 201) {
    notification.warning({
      message: '提示',
      description: data.message,
    });
  }
  if (data.code === 401 && !(data.result && data.result.isLogin)) {
    notification.error({
      message: 'Unauthorized',
      description: '用户信息失效',
    });
    goLoginPage(router);
  }

  if (data.code === 402) {
    notification.error({
      message: 'Forbidden',
      description: '请登录',
    });
    goLoginPage(router);
  }
  if (data.code === 500) {
    notification.warning({
      message: '提示',
      description: data.message,
    });
  }
  return data;
};

// Add a response interceptor
request.interceptors.response.use(responseHandler, errorHandler);

export { AxiosResponse };

export default request;

export const get = (url: string, params: object): AxiosPromise => {
  return request({
    method: 'get',
    url,
    params,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
  });
};

export function post<T = any>(url: string, data = {}) {
  return request.post<any, T>(url, qs.stringify(data), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
  });
}

export function form<T = any>(url: string, data) {
  return request.post<any, T>(url, data);
}

export const getJson = (url: string): AxiosPromise => {
  return request({
    method: 'get',
    url,
  });
};

// 文件下载
export const downloadFile = (url: string, data: object): AxiosPromise => {
  return request({
    method: 'post',
    url,
    data: qs.stringify(data),
    responseType: 'blob',
  });
};

export function postJson<T = any>(url: string, data = {}) {
  return request.post<any, T>(url, data, { headers: { 'Content-Type': 'application/json' } });
}

export const postJsonDownload = (url: string, data: object): AxiosPromise => {
  return request({
    method: 'post',
    url,
    data,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json',
    },
  });
};
export const customUrlPost = (url: string, data: object): AxiosPromise => {
  return request({
    method: 'post',
    url,
    data,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
  });
};

// 跳转到csa页面
export const goLoginPage = (router: any): void => {
  //   const { fullPath } = router.currentRoute.value;
  //   const frontUrl = (window as any).g.staticUrl;
  //   const baseURL: string = (window as any).g.baseURL;
  //   const defalutUrl: string =
  //     (window as any).g.routerMode === 'hash' ? `${frontUrl}#/default` : `${frontUrl}default`; // 前端跳板页
  //   const href = `${baseURL}/casLogin/toLogin?service=${encodeURIComponent(
  //     fullPath,
  //   )}&front=${encodeURIComponent(defalutUrl)}`;
  //   window.location.href = href;
  //   const route = useRouter();
  console.log('router', router);
  router.push('/user/login');
};

// 退出登录，跳转到单点登录页面
export const toExit = (router: any): void => {
  //   const { fullPath } = router.currentRoute.value;
  //   const frontUrl: string = (window as any).g.staticUrl;
  //   const baseURL: string = (window as any).g.baseURL;
  //   const defalutUrl: string =
  //     (window as any).g.routerMode === 'hash' ? `${frontUrl}#/default` : `${frontUrl}default`; // 前端跳板页
  //   const href = `${baseURL}/casLogin/toExit?service=${encodeURIComponent(
  //     fullPath,
  //   )}&front=${encodeURIComponent(defalutUrl)}`;
  //   window.location.href = href;
  router.push('/user/login');
};
